
local getmetatable = getmetatable
local setmetatable = setmetatable
local module = module
local require = require
local print = print
local type = type
local error = error
local string = string
local pcall = pcall
local package = package
local io = io
local assert = assert

module('eg.music.MusicLibrary')
_VERSION='0.1'

local Music = require('eg.music.Music')

do

local musicLibrary = {}
musicLibrary.library = {}

local function loadFile(self, name)
    music = {}
    inFile = assert(io.open(name, "r"))
    inFile:read() -- skip header
    line = inFile:read()
    while line do
        music[#music+1] = Music(line)
        line = inFile:read()
    end
    io.close()
    self.library = music
end

local function select(self, music)
    self.looking = music
end

local function findArtist(self, artist)
    for i=1,#self.library do
        self.library[i].selected = (self.library[i].artist == artist)
    end
end

local function findAlbum(self, album)
    for i=1,#self.library do
        self.library[i].selected = (self.library[i].album == album)
    end
end

local function findGenre(self, genre)
    for i=1,#self.library do
        self.library[i].selected = (self.library[i].genre == genre)
    end
end

local function findYear(self, year)
    for i=1,#self.library do
        self.library[i].selected = (self.library[i].year == year)
    end
end

local function displayCount(self)
    count = 0
    for i=1,#self.library do
        if self.library[i].selected then count = count + 1 end
    end
    return count
end

local function displayContents(self)
    displayed = {}
    for i=1,#self.library do
        if self.library[i].selected then
            displayed[#displayed + 1] = self.library[i]
        end
    end

    return displayed
end

function __call()

    musicLibrary.loadFile = loadFile
    musicLibrary.select = select
    musicLibrary.findArtist = findArtist
    musicLibrary.findAlbum = findAlbum
    musicLibrary.findGenre = findGenre
    musicLibrary.findYear = findYear
    musicLibrary.displayCount = displayCount
    musicLibrary.displayContents = displayContents

    return musicLibrary
end

end

setmetatable(_M, _M)
